<template>
  <div class="search">
      <!-- 顶部 -->
      <van-nav-bar
        title="搜索中心"
        left-arrow
        @click-left="$router.back()"
        />
        <!-- 搜索框 -->
        <van-search
        show-action
        placeholder="请输入搜索关键词"
        shape="round"
        v-model.trim="keyword"
        @input="hGetSuggestion_with_jie_liu_lodash"
        >
        <div slot="action" @click="Hsearch" >搜索</div>
        </van-search>
        <!-- 联想记录 -->
        <van-cell-group v-if="keyword">
        <van-cell v-for="(item, idx) in csuggestion" :key="idx" @click='searchSuggestion(idx)'  icon="search" >
            <div v-html="item"></div>
        </van-cell>
        </van-cell-group>
        <!-- 历史记录 -->
        <van-cell-group v-else>
        <van-cell title="历史记录" />
        <van-cell @click="$router.push('/search/result?keyword='+item)" v-for="(item, index) in history" :key="index" :title="item"  >
            <van-icon name="close" @click.stop="delHistory(index)"/>
        </van-cell>
        </van-cell-group>
  </div>
</template>

<script>
import { setItem, getItem } from '@/utils/storage'
import { sendKeyword } from '@/api/search'
import _ from 'lodash'
const SEARCHHISTORY_KEY = 'searchHistory'
export default {
  name: 'search',
  data () {
    return {
      keyword: '',
      suggestion: [],
      history: getItem(SEARCHHISTORY_KEY) || []
    }
  },
  computed: {
    // 高亮显示属性
    csuggestion () {
      const regexp = new RegExp(this.keyword)
      const arr = this.suggestion.map(str => {
        return str.replace(regexp, (obj) => {
          return `<span style="color:red;">${obj}</span>`
        })
      })
      return arr
    }
  },
  methods: {
    // 节流操作
    hGetSuggestion_with_jie_liu_lodash: _.throttle(async function () {
      if (this.keyword === '') {
        this.suggestion = []
        return false
      }
      const res = await sendKeyword(this.keyword)
      this.suggestion = res.data.data.options
    }, 500),
    // 用户点击了搜索按钮
    Hsearch () {
      if (this.keyword === '') {
        return false
      }
      this.addHistory(this.keyword)
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: this.keyword
        }
      })
    },
    // 点击联想记录之后 触发将点击向添加到搜索记录中去
    searchSuggestion (idx) {
      console.log(111);
      // 将联想记录中的点击的那项添加到记录中
      this.addHistory(this.suggestion[idx])
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: this.suggestion[idx]
        }
      })
    },
    // 添加搜索记录
    addHistory (str) {
      const index = this.history.findIndex(item => item === str)
      if (index !== -1) {
        this.history.splice(index, 1)
      }
      this.history.unshift(str)
      setItem(SEARCHHISTORY_KEY, this.history)
    },
    delHistory (idx) {
      this.history.splice(idx, 1)
      setItem(SEARCHHISTORY_KEY, this.history)
    }
  }
}
</script>

<style lang='less' scoped>

</style>
